package com.sunspring.jbug.service;

import com.sunspring.jbug.bean.UserInfo;
import com.sunspring.jbug.common.exception.JbugException;
import com.sunspring.jbug.support.EmailSupport;
import com.sunspring.jbug.support.LocalCache;
import com.sunspring.jbug.util.CommonUtil;
import com.sunspring.jbug.util.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author wulei
 * @date 2019-03-01
 **/
@Service
public class EmailService {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailSupport emailSupport;


    /**
     * 注册发送邮箱验证码
     * @param email 邮箱
     */
    public void regSendVerificationCode(String email) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(email);
        List<UserInfo> list = userService.getSelective(userInfo);
        if (!CollectionUtils.isEmpty(list)) {
            throw new JbugException("该邮箱已被注册");
        }
        String code = CommonUtil.verificationCode();
        LocalCache.CACHE.put(email,code);
        emailSupport.doSend(code,email);
    }

    /**
     * 邮箱注册
     * @param userInfo 用户信息
     * @param code 用户输入的验证码
     */
    public void regByEmail(UserInfo userInfo, String code) {
        String cacheVerificationCode = LocalCache.CACHE.getIfPresent(userInfo.getUsername());
        if (cacheVerificationCode == null) {
            throw new JbugException("验证阿已过期请重新获取");
        }
        //验证码校验
        if (!StringUtils.equals(code,cacheVerificationCode)) {
            throw new JbugException("验证码错误");
        }
        userInfo.setPassword(Md5Util.md5(userInfo.getPassword()));
        userService.add(userInfo);
    }
}
